
package com.xiaoma.myaudience.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.text.TextUtils;

/**
 * <br/>
 * 图片工具类. <br/>
 * 用于读取保存本地图片,对图片进行缩放变形等操作 <br/>
 * TODO 暂时只有图片存取
 * 
 * @author wjying
 */
public class PicUtils {
    private static final String TAG = "PicUtil";


    /**
     * 从文件读取图片.
     * 
     * @param res
     * @param path 文件路径
     * @return
     */
    public static Bitmap readBitmap(Resources res, File file) {
        try {
            return readBitmap(res, new FileInputStream(file));
        } catch (FileNotFoundException e) {
            Logger.e(TAG, "readDrawalbe error!!!!!", e);
        }
        return null;
    }

    /**
     * 从文件读取图片.
     * 
     * @param res
     * @param path 文件路径
     * @return
     */
    public static Bitmap readBitmap(Resources res, String path) {
        try {
            return readBitmap(res, new FileInputStream(path));
        } catch (FileNotFoundException e) {
            Logger.e(TAG, "readDrawalbe error!!!!!", e);
        }
        return null;
    }

    /**
     * 从文件读取图片.
     * 
     * @param res
     * @param is
     * @return
     */
    public static Bitmap readBitmap(Resources res, InputStream is) {
        return BitmapFactory.decodeResourceStream(res, null, is, null, getBitmapOptions());
    }

    /**
     * 从文件读取图片.
     * 
     * @param filename
     */
	public static byte[] readFileImage(String filename)throws IOException{
		BufferedInputStream bufferedInputStream=new BufferedInputStream(
				new FileInputStream(filename));
		int len =bufferedInputStream.available();
		byte[] bytes=new byte[len];
		int r=bufferedInputStream.read(bytes);
		if(len !=r){
			bytes=null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}
	
    /**
     * <br/>
     * 保存图片.
     * 
     * @param is
     * @param path
     * @return 图片保存路径,如果返回空 说明保存不成功
     */
    public static String saveBitmap(InputStream is, String name, String size) {
        Bitmap bm = BitmapFactory
                .decodeStream(new FlushedInputStream(is), null, getBitmapOptions());
        if (bm != null) {
            saveBitmap(bm, name, size);
        }

        return null;
    }

    /**
     * TODO ... <br/>
     * 保存图片.
     * 
     * @param bm
     * @param name
     * @return
     */
    public static Bitmap saveBitmap(Bitmap bm, String path, String size) {
        if (bm != null) {
            if (SystemUtils.isSDCardMounted()) {
                File f = new File(path);
                FileUtils.createFile(f);
                if (f.exists()) {
                    FileOutputStream fOut = null;
                    try {
                        fOut = new FileOutputStream(f);

                        int[] s = parseSize(size);
                        if (s != null) {
                            bm = resizePic(bm, s[0], s[1]);
                        }
                        if (bm != null) {
                            bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                        }
                        fOut.flush();
                        return bm;
                    } catch (Exception e) {
                        Logger.e(TAG, "saveBitmap error!!!!!", e);
                    } finally {
                        if (fOut != null) {
                            try {
                                fOut.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    /**
     * 对图片进行缩放
     * 
     * @param src
     * @param width
     * @param height
     * @return
     */
    public static Bitmap resizePic(Bitmap src, int width, int height) {
        Bitmap bitmap = null;

        if (src == null || width == 0 || height == 0) {
            Logger.e(TAG, "resizePic error!!! " + src + ",width="+width+",height="+height);
            return bitmap;
        }

        try {
            final int srcW = src.getWidth();
            final int srcH = src.getHeight();
            final float sW = ((float)srcW) / width;
            final float sH = ((float)srcH) / height;
            if (sW == 1 && sH == 1) {
                // 需要的尺寸一致,直接返回
                bitmap = src;
            } else if (sW == sH) {
                // 长宽比一致
                bitmap = src;//Bitmap.createScaledBitmap(src, width, height, false);
            } else if (sW > sH) {
                int offsetX = (int)((srcW - width * sH) / 2);
                int offsetY = 0;
//                Matrix matrix = new Matrix();
//                matrix.postScale(1 / sH, 1 / sH);
//                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW - 2 * offsetX, srcH, matrix, false);
                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW - 2 * offsetX, srcH);
            } else {
                int offsetX = 0;
                int offsetY = (int)((srcH - height * sW) / 2);
//                Matrix matrix = new Matrix();
//                matrix.postScale(1 / sW, 1 / sW);
//                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW, srcH - 2 * offsetY, matrix, false);
                bitmap = Bitmap.createBitmap(src, offsetX, offsetY, srcW, srcH - 2 * offsetY);
            }
        } catch (Exception e) {
            Logger.e(TAG, "resizePic error!!!", e);
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
        } finally {
            if (src != null && src != bitmap) {
                src.recycle();
            }
        }
        
        return bitmap;
    }
    
    /**
     * 返回大小字符串
     * 
     * @param width
     * @param height
     * @return
     */
    public static String composeSize(int width, int height) {
        return String.format("%dx%d", width, height);
    }

    /**
     * 返回大小数组
     * 
     * @param size
     * @return
     */
    public static int[] parseSize(String size) {
        try {
            if (!TextUtils.isEmpty(size)) {
                String[] strs = size.split("x");
                if (strs != null && strs.length == 2) {
                    int w = Integer.parseInt(strs[0]);
                    int h = Integer.parseInt(strs[1]);
                    return new int[] {
                            w, h
                    };
                }
            }
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * <br/>
     * 获取图片读取写入时参数. <br/>
     * TODO 暂时全部返回 {@link Bitmap.CompressFormat.PNG}
     * 
     * @return
     */
    private static BitmapFactory.Options getBitmapOptions() {
        // TODO 这个opt需不需要有什么要求
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        return opt;
    }

    /**
     * <br/>
     * 根据名称返回压缩格式. <br/>
     * TODO 暂时全部返回 {@link Bitmap.CompressFormat.PNG}
     * 
     * @param name
     * @return
     */
    @SuppressWarnings("unused")
    private static Bitmap.CompressFormat getBimatCompressFormat(String name) {
        // String format = StringUtils.getFormatFromName(name);
        // if (!TextUtils.isEmpty(format)) {
        // format = format.toUpperCase();
        // }

        return Bitmap.CompressFormat.PNG;
    }

    /**
     * TODO ... <br/>
     * 从原来拷贝，作用不明 <br/>
     * 在从InputStream流保存图片时有用到
     * 
     * @author
     */
    public static class FlushedInputStream extends FilterInputStream {
        /*
         * An InputStream that skips the exact number of bytes provided, unless
         * it reaches EOF.
         */
        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) {
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                    int b = read();
                    if (b < 0) {
                        break; // we reached EOF
                    } else {
                        bytesSkipped = 1; // we read one byte
                    }
                }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }
    
    public static Bitmap getImageThumbnail(String imagePath, int width, int height) {  
        Bitmap bitmap = null;  
        BitmapFactory.Options options = new BitmapFactory.Options();  
        options.inJustDecodeBounds = true;  
        // 获取这个图片的宽和高，注意此处的bitmap为null  
        bitmap = BitmapFactory.decodeFile(imagePath, options);  
        options.inJustDecodeBounds = false; // 设为 false  
        // 计算缩放比  
        int h = options.outHeight;  
        int w = options.outWidth;  
        int beWidth = w / width;  
        int beHeight = h / height;  
        int be = 1;  
        if (beWidth < beHeight) {  
            be = beWidth;  
        } else {  
            be = beHeight;  
        }  
        if (be <= 0) {  
            be = 1;  
        }  
        options.inSampleSize = be;  
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false  
        bitmap = BitmapFactory.decodeFile(imagePath, options);  
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象  
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,  
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);  
        return bitmap;  
    }  

}
